import { resourceEntApi } from '@/api';
import { pageOpeTypeEnum } from '@/common';
import YmCollaPanes from '@/components/YmCollaPanes';
import { App, Button, Form, Input, InputNumber } from 'antd';
import { add, isEmpty, multiply } from 'lodash';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useYmAliOss, YmAddPageLayout, YmUpload, type YmAddPageLayoutProps } from 'ym-design';
import HeaderTitle from './HeaderTitle';
import QueTable from './QueTable';

import { SourceSelectModal } from '@/components/SourceSelect';
import Source from '@/components/SourceSelect/Entity/Source';
import { v4 as uuid } from 'uuid';

// '单选题选择' | '多选题选择' | '课件' | '判断题选择';

import { ShelfPaper } from '@/api/Shelf';
import { CategoryCascader } from '@/components/CategoryCascader';
import OStyle from './index.less';

const { PaneItem } = YmAddPageLayout;

const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};

const formItemLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 18 },
};

type IScoreDetail = {
  score: number | undefined | null;
  questions: any[];
  modalOpen: number | undefined;
  questionsModalVal: Source[];
};

interface AddTestPaperProps {
  useFor?: 'sourceLibrary' | 'Shelf';
  onBack?(): void;
  classId?: string;
  parClassId?: string;
}
const plantType = process.env.processEnvDetail.REACT_APP_PLATFORM;
function AddTestPaper({ useFor = 'sourceLibrary', onBack, classId, parClassId }: AddTestPaperProps) {
  // 使用aliyunoss进行操作
  const customRequest = useYmAliOss();
  const { message } = App.useApp();

  const [searchParam] = useSearchParams();
  const navigator = useNavigate();
  const type = useFor === 'Shelf' ? 'add' : searchParam.get('type');
  const parentId = searchParam.get('parentId');
  const resourceId = searchParam.get('resourceId');
  const [form] = Form.useForm();
  const [loadingDetail, setLoadingDetail] = useState({
    subBtnDis: false,
    viewLoading: false,
  });
  const [collPanesActiveKeys, setCollPanesActiveKeys] = useState([0, 1, 2, 3]);
  const [totalScore, setTotalScore] = useState<number>(0);

  //单选题
  const [sChoiceQueScoreDetail, setSChoiceQueScoreDetail] = useState<IScoreDetail>({
    score: undefined,
    questions: [],
    modalOpen: undefined,
    questionsModalVal: [],
  });

  //多选题
  const [mChoiceQueScoreDetail, setMChoiceQueScoreDetail] = useState<IScoreDetail>({
    score: undefined,
    questions: [],
    modalOpen: undefined,
    questionsModalVal: [],
  });

  // 判断题
  const [judgeQueScoreDetail, setJudgeQueScoreDetail] = useState<IScoreDetail>({
    score: undefined,
    questions: [],
    modalOpen: undefined,
    questionsModalVal: [],
  });

  const goBackToList = () => {
    if (plantType === 'boss') {
      if (useFor === 'sourceLibrary') {
        navigator('/resourceLibrary/testPaper');
      } else if (useFor === 'Shelf') {
        onBack?.();
      }
    } else {
      navigator('/cusResLib/testPaper');
    }
  };

  function _dealWidthScoreDetail(): boolean | any[] {
    function _getQue(scoreDetail: IScoreDetail, queArrayList: any[]) {
      const { questions, score } = scoreDetail;

      questions.forEach((queItem: any, index: number) => {
        const {
          origin: { modifyTime, platformQuestion },
        } = queItem;
        const { selectItems, anwserItems } = platformQuestion;
        let anwserItemList = [];
        let selectItemList = [];
        try {
          anwserItemList = JSON.parse(anwserItems);
          selectItemList = JSON.parse(selectItems);
        } catch (err) {
          console.log('--AddTestPaper--_getQue--jsonParse--err--:', index);
        }
        queArrayList.push({ ...platformQuestion, anwserItemList, selectItemList, score, modifyTime });
      });
    }
    function _getEntQue(scoreDetail: IScoreDetail, queArrayList: any[]) {
      const { questions, score } = scoreDetail;
      const questionType = questions[0].origin.coursewareGroup;
      const num = questions.length;
      const questionList: any[] = [];
      questions.forEach((queItem: any, index: number) => {
        // 编辑试卷时候，回填的，BOSS端数据格式(有platformQuestion)
        if (queItem.origin.platformQuestion) {
          const {
            origin: { platformQuestion },
          } = queItem;
          questionList.push({ ...platformQuestion });
        } else {
          // 添加或者编辑时候，从考题列表添加的题目会走这里
          const obj = Object.assign({}, queItem.origin.safeQuestion);
          obj.selectItemList = JSON.parse(obj.selectItems);
          obj.answerItemList = JSON.parse(obj.anwserItems);
          obj.questionType = obj.type;
          delete obj.selectItems;
          delete obj.anwserItems;
          questionList.push(obj);
        }
      });
      queArrayList.push({ questionList, num, questionType, score }); // 在这里push类型
    }

    if (isEmpty(sChoiceQueScoreDetail.questions) && sChoiceQueScoreDetail.score) {
      message.error('请选择单选题');
      return false;
    } else if (!isEmpty(sChoiceQueScoreDetail.questions) && !sChoiceQueScoreDetail.score) {
      message.error('请输入单选题每题分数');
      return false;
    }

    if (isEmpty(mChoiceQueScoreDetail.questions) && mChoiceQueScoreDetail.score) {
      message.error('请选择多选题');
      return false;
    } else if (!isEmpty(mChoiceQueScoreDetail.questions) && !mChoiceQueScoreDetail.score) {
      message.error('请输入多选题每题分数');
      return false;
    }

    if (isEmpty(judgeQueScoreDetail.questions) && judgeQueScoreDetail.score) {
      message.error('请选择判断题');
      return false;
    } else if (!isEmpty(judgeQueScoreDetail.questions) && !judgeQueScoreDetail.score) {
      message.error('请输入判断题每题分数');
      return false;
    }

    if (!totalScore) {
      message.error('及格分数不得大于试卷满分');
      return false;
    }

    const passScore = form.getFieldValue('passScore');
    if (passScore > totalScore) {
      message.error('及格分数不得大于试卷满分');
      return false;
    }

    console.log('--提交--sChoiceQueScoreDetail.sChoiceQueScoreDetail---：', sChoiceQueScoreDetail.questions);

    const queArrayList: any[] = [];
    if (plantType === 'boss') {
      _getQue(sChoiceQueScoreDetail, queArrayList);
      _getQue(mChoiceQueScoreDetail, queArrayList);
      _getQue(judgeQueScoreDetail, queArrayList);
    } else {
      if (sChoiceQueScoreDetail.questions.length > 0) _getEntQue(sChoiceQueScoreDetail, queArrayList);
      if (mChoiceQueScoreDetail.questions.length > 0) _getEntQue(mChoiceQueScoreDetail, queArrayList);
      if (judgeQueScoreDetail.questions.length > 0) _getEntQue(judgeQueScoreDetail, queArrayList);
    }

    return queArrayList;
  }
  // 提交
  const _formSub = (subType: number) => {
    form
      .validateFields()
      .then((values) => {
        console.log('--AddTestPaper--values--:', values);
        const questions = _dealWidthScoreDetail();
        if (!Array.isArray(questions)) return;
        setLoadingDetail({ subBtnDis: true, viewLoading: true });
        const { picUrl, name, passScore, classId } = values;
        const coverUrl = picUrl?.[0].url ?? picUrl?.[0].response;
        const subData: any = {
          parentId,
          // coursewareType: 'paper',
          cover: coverUrl,
          name,
          // picUrl: coverUrl,
          questionTypeList: questions,
          passScore,
          totalScore,
          scoreInfo: totalScore,
          // questions,
        };
        console.log('--addTestPaper--subData--:', subData);
        let requestApi;
        if (plantType === 'boss') {
          if (useFor === 'sourceLibrary') {
            if (type === pageOpeTypeEnum['add']) {
              requestApi = resourceEntApi.createCourseWare(subData);
            } else if (type === pageOpeTypeEnum['edit']) {
              subData.coursewareId = resourceId;
              requestApi = resourceEntApi.updateCourseWare(subData);
            }
          } else if (useFor === 'Shelf') {
            delete subData.parentId;
            requestApi = ShelfPaper.createOrUpdate({
              ...subData,
              shelvesPaper: 1,
              classId,
            });
          }
        } else {
          if (type === pageOpeTypeEnum['add']) {
            requestApi = resourceEntApi.createPaper(subData);
          } else if (type === pageOpeTypeEnum['edit']) {
            subData.paperId = resourceId;
            requestApi = resourceEntApi.createPaper(subData);
          }
        }

        if (!requestApi) {
          return message.error('type 未定义');
        }

        requestApi
          .then((res: any) => {
            const { msg } = res;
            message.success(msg || `${type === pageOpeTypeEnum['add'] ? '添加' : '编辑'}成功`);
            if (subType === 1) {
              //保存
              goBackToList();
            } else {
              //保存并继续
              form.resetFields();
              setSChoiceQueScoreDetail({
                score: undefined,
                questions: [],
                modalOpen: undefined,
                questionsModalVal: [],
              });
              setMChoiceQueScoreDetail({
                score: undefined,
                questions: [],
                modalOpen: undefined,
                questionsModalVal: [],
              });
              setJudgeQueScoreDetail({
                score: undefined,
                questions: [],
                modalOpen: undefined,
                questionsModalVal: [],
              });
              setTotalScore(0);
            }
          })
          .catch((err: any) => {
            console.log('--AddSTestPaper--formSub--err--:', err);
          })
          .finally(() => {
            setLoadingDetail({ subBtnDis: false, viewLoading: false });
          });
      })
      .catch((err) => {
        console.log('--AddSTestPaper--form--err--:', err);
        setLoadingDetail({ subBtnDis: false, viewLoading: false });
      });
  };

  // 保存
  const sub = () => {
    _formSub(1);
  };

  // 保存并继续添加
  const subAndContinue = () => {
    _formSub(2);
  };

  const operationFooter = useMemo(() => {
    const operationBtn = [
      <div key="totalScore" className={OStyle.row_number}>
        <div style={{ width: 42 }}> 满分：</div>
        <span className={OStyle.number_bold}>{totalScore}</span>分
      </div>,
      <Button key="subOnce" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={sub}>
        保存
      </Button>,
      <Button key="subContinue" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={subAndContinue}>
        保存并继续添加
      </Button>,
    ];
    switch (type) {
      case pageOpeTypeEnum['add']:
        return operationBtn;
      case pageOpeTypeEnum['edit']:
        operationBtn.splice(2, 1); //subst start length
        return operationBtn;
    }
  }, [type, loadingDetail, totalScore, sChoiceQueScoreDetail, mChoiceQueScoreDetail, judgeQueScoreDetail]);

  //选择题目
  function _choiceQue(values: any[]) {
    const currQuestions = values.map((valItem: any, index: number) => ({
      ...valItem,
      index,
    }));

    // modal回显
    const currQuestionsModalVal = currQuestions.map(
      (currQueItem: any) =>
        new Source(
          currQueItem.id,
          currQueItem.name,
          currQueItem.type,
          currQueItem.from,
          currQueItem.isFolder,
          currQueItem.createTime,
          currQueItem.updateTime,
          currQueItem.origin,
        ),
    );
    return {
      questions: currQuestions,
      questionsModalVal: currQuestionsModalVal,
    };
  }

  //删除题目
  function _removeQue(scoreDetail: { questions: any[]; questionsModalVal: any[] }, id: string) {
    const currQuestions = scoreDetail.questions
      .filter((queItem: any) => queItem.id !== id)
      .map((queItem, index) => ({ ...queItem, index }));
    const currQuestionsModalVal = scoreDetail.questionsModalVal.filter((queModalItem) => queModalItem.id !== id);
    return {
      questions: currQuestions,
      questionsModalVal: currQuestionsModalVal,
    };
  }

  // 选题单选题
  const choiceSChoiceQue = (values: any[]) => {
    console.log('---选题单选题--values--:', values);

    const tempScoreDetail = _choiceQue(values);

    setSChoiceQueScoreDetail((prev) => ({
      ...prev,
      ...tempScoreDetail,
    }));
  };

  // 单选题删除
  const handleSchoiceQuestionsRemove = (id: string) => {
    console.log('--单选题删除--id---:', id);
    const tempScoreDetail = _removeQue(sChoiceQueScoreDetail, id);

    setSChoiceQueScoreDetail((prev) => ({
      ...prev,
      ...tempScoreDetail,
    }));
  };

  //多选题选择
  const choiceMChoiceQue = (values: any[]) => {
    const tempScoreDetail = _choiceQue(values);

    setMChoiceQueScoreDetail((prev) => ({
      ...prev,
      ...tempScoreDetail,
    }));
  };

  //多选题删除
  const handleMchoiceQuestionsRemove = (id: string) => {
    const tempScoreDetail = _removeQue(mChoiceQueScoreDetail, id);
    setMChoiceQueScoreDetail((prev) => ({
      ...prev,
      ...tempScoreDetail,
    }));
  };

  //多选题选择
  const choiceJudgeQue = (values: any[]) => {
    const tempScoreDetail = _choiceQue(values);
    setJudgeQueScoreDetail((prev) => ({
      ...prev,
      ...tempScoreDetail,
    }));
  };

  //多选题删除
  const handleJudgeQuestionsRemove = (id: string) => {
    const tempScoreDetail = _removeQue(judgeQueScoreDetail, id);
    setJudgeQueScoreDetail((prev) => ({
      ...prev,
      ...tempScoreDetail,
    }));
  };

  // 时时计算总分
  useEffect(() => {
    const sChoiceQueScore = multiply(sChoiceQueScoreDetail.questions.length, sChoiceQueScoreDetail.score || 0);
    const mChoiceQueScore = multiply(mChoiceQueScoreDetail.questions.length, mChoiceQueScoreDetail.score || 0);
    const judgeQueScore = multiply(judgeQueScoreDetail.questions.length, judgeQueScoreDetail.score || 0);
    const tempTotalScore = add(judgeQueScore, add(sChoiceQueScore, mChoiceQueScore));
    setTotalScore(tempTotalScore);
  }, [sChoiceQueScoreDetail, mChoiceQueScoreDetail, judgeQueScoreDetail]);

  useEffect(() => {
    if (type === pageOpeTypeEnum['edit']) {
      resourceEntApi.getPaperDetailById({ coursewareId: resourceId }).then((res: any) => {
        res.data.picUrl = res.data.cover;
        const {
          data: { name, picUrl, passScore, questionTypeList, totalScore },
        } = res;
        let questions: any[] = [];
        try {
          questions = questionTypeList;
        } catch (err) {
          console.log('--jsonParse--getCourseWareById--questionsInfo--err--');
        }
        // TODO: from: "boss"
        const Quefrom = 'boss'; //process.env.processEnvDetail.REACT_APP_PLATFORM as 'platform' | 'government' | 'boss';

        console.log('--edit--questions--:', questions);

        const sChoiceQueScoreDetail = {
          score: undefined,
          questions: [],
          modalOpen: undefined,
          questionsModalVal: [],
        };
        const mChoiceQueScoreDetail = {
          score: undefined,
          questions: [],
          modalOpen: undefined,
          questionsModalVal: [],
        };
        const judgeQueScoreDetail = {
          score: undefined,
          questions: [],
          modalOpen: undefined,
          questionsModalVal: [],
        };

        questions.forEach((queItem: any, index: number) => {
          queItem.questionList.forEach((el: any) => {
            const questionId = el.guid;
            const content = el.content;
            const type = el.questionType;
            const Quefrom = 'government';
            const tempCreateTime = '2023-07-24 00:00:00';
            const tempModifyTime = '2023-07-24 00:00:00';
            const score = queItem.score;
            const newItem = {
              id: el.guid,
              name: el.content,
              isFolder: false,
              type: el.questionType,
              origin: { platformQuestion: { ...el } },
            };
            const newSource = new Source(questionId, content, type, Quefrom, false, tempCreateTime, tempModifyTime, {
              // modifyTime: tempModifyTime,
              platformQuestion: { ...el },
            });
            if (el.questionType == 100) {
              sChoiceQueScoreDetail.score = score;
              (sChoiceQueScoreDetail.questions as any[]).push(newItem);
              (sChoiceQueScoreDetail.questionsModalVal as Source[]).push(newSource);
            }
            if (el.questionType == 200) {
              mChoiceQueScoreDetail.score = score;
              (mChoiceQueScoreDetail.questions as any[]).push(newItem);
              (mChoiceQueScoreDetail.questionsModalVal as Source[]).push(newSource);
            }
            if (el.questionType == 300) {
              judgeQueScoreDetail.score = score;
              (judgeQueScoreDetail.questions as any[]).push(newItem);
              (judgeQueScoreDetail.questionsModalVal as Source[]).push(newSource);
            }
          });
        });

        console.log('--单选题---mChoiceQueScoreDetail.questions--：', mChoiceQueScoreDetail.questions);
        form.setFieldsValue({ name, picUrl: picUrl ? [{ uid: uuid(), url: picUrl }] : undefined, passScore });
        setTotalScore(totalScore);
        setSChoiceQueScoreDetail({
          ...sChoiceQueScoreDetail,
          questions: (sChoiceQueScoreDetail.questions as any[]).map((queItem, index) => ({ ...queItem, index })),
        });
        setMChoiceQueScoreDetail({
          ...mChoiceQueScoreDetail,
          questions: (mChoiceQueScoreDetail.questions as any[]).map((queItem, index) => ({ ...queItem, index })),
        });
        setJudgeQueScoreDetail({
          ...judgeQueScoreDetail,
          questions: (judgeQueScoreDetail.questions as any[]).map((queItem, index) => ({ ...queItem, index })),
        });
      });
    }
  }, []);

  console.log(classId, parClassId);
  const [formItemProps] = CategoryCascader.useFieldLevelTwo(classId && parClassId ? [parClassId, classId] : undefined);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          goBackToList();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );

  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem
        tabKey="tab1"
        label={(type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + '试卷'}
        className="pane_tab1"
      >
        <div className="ym_detail_grid">
          <Form layout="horizontal" labelAlign="right" form={form} {...formItemLayout} initialValues={{ classId }}>
            <YmCollaPanes
              collPanesActiveKeys={collPanesActiveKeys}
              // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
              paneKey={0}
              collapsible={false}
              headerTitle="基本信息"
            >
              <div>
                <Form.Item name="name" label="试卷名称" rules={requireRules('请输入试卷名称')}>
                  <Input placeholder="请输入" autoComplete="off" showCount maxLength={18} />
                </Form.Item>
                {useFor === 'Shelf' ? (
                  <Form.Item label="所属分类" rules={[{ required: true }]} name="classId" {...formItemProps}>
                    <CategoryCascader />
                  </Form.Item>
                ) : null}
                <Form.Item label="封面图">
                  <Form.Item name="picUrl" noStyle>
                    <YmUpload
                      maxCount={1}
                      cardWidth={140}
                      cardHeight={140}
                      accept="image/*"
                      customRequest={customRequest}
                    >
                      封面图
                    </YmUpload>
                  </Form.Item>
                  <p className="safe-edu_upload_warning">图片宽高比例以1.875:1为宜，如：750*400</p>
                </Form.Item>
                <Form.Item name="passScore" label="及格分数" rules={requireRules('请输入及格分数')}>
                  <InputNumber placeholder="请输入" min={0} />
                </Form.Item>
              </div>
            </YmCollaPanes>

            <YmCollaPanes
              collPanesActiveKeys={collPanesActiveKeys}
              // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
              paneKey={1}
              collapsible={false}
              headerTitle={
                <HeaderTitle
                  scoreTypeName="单选题"
                  score={sChoiceQueScoreDetail.score}
                  scoreLength={sChoiceQueScoreDetail.questions.length}
                  onChangeScore={(value) => {
                    setSChoiceQueScoreDetail((prev) => ({ ...prev, score: value }));
                  }}
                />
              }
            >
              <div className={OStyle.pane_content_body}>
                <QueTable
                  scoreTypeName="单选题"
                  questions={sChoiceQueScoreDetail.questions}
                  onAddQuestion={() => {
                    setSChoiceQueScoreDetail((prev) => ({ ...prev, modalOpen: Math.random() }));
                  }}
                  hideModifyTime={true}
                  onQuestionsRemove={handleSchoiceQuestionsRemove}
                />
                <SourceSelectModal
                  openDep={sChoiceQueScoreDetail.modalOpen}
                  preSet="单选题选择"
                  onChange={choiceSChoiceQue}
                  value={sChoiceQueScoreDetail.questionsModalVal}
                ></SourceSelectModal>
              </div>
            </YmCollaPanes>

            <YmCollaPanes
              collPanesActiveKeys={collPanesActiveKeys}
              // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
              paneKey={2}
              collapsible={false}
              headerTitle={
                <HeaderTitle
                  scoreTypeName="多选题"
                  score={mChoiceQueScoreDetail.score}
                  scoreLength={mChoiceQueScoreDetail.questions.length}
                  onChangeScore={(value) => {
                    setMChoiceQueScoreDetail((prev) => ({ ...prev, score: value }));
                  }}
                />
              }
            >
              <div className={OStyle.pane_content_body}>
                <QueTable
                  scoreTypeName="多选题"
                  questions={mChoiceQueScoreDetail.questions}
                  onAddQuestion={() => {
                    setMChoiceQueScoreDetail((prev) => ({ ...prev, modalOpen: Math.random() }));
                  }}
                  hideModifyTime={true}
                  onQuestionsRemove={handleMchoiceQuestionsRemove}
                />
                <SourceSelectModal
                  openDep={mChoiceQueScoreDetail.modalOpen}
                  preSet="多选题选择"
                  onChange={choiceMChoiceQue}
                  value={mChoiceQueScoreDetail.questionsModalVal}
                ></SourceSelectModal>
              </div>
            </YmCollaPanes>

            <YmCollaPanes
              collPanesActiveKeys={collPanesActiveKeys}
              // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
              paneKey={3}
              collapsible={false}
              headerTitle={
                <HeaderTitle
                  scoreTypeName="判断题"
                  score={judgeQueScoreDetail.score}
                  scoreLength={judgeQueScoreDetail.questions.length}
                  onChangeScore={(value) => {
                    setJudgeQueScoreDetail((prev) => ({ ...prev, score: value }));
                  }}
                />
              }
            >
              <div className={OStyle.pane_content_body}>
                <QueTable
                  scoreTypeName="判断题"
                  questions={judgeQueScoreDetail.questions}
                  onAddQuestion={() => {
                    setJudgeQueScoreDetail((prev) => ({ ...prev, modalOpen: Math.random() }));
                  }}
                  hideModifyTime={true}
                  onQuestionsRemove={handleJudgeQuestionsRemove}
                />

                <SourceSelectModal
                  openDep={judgeQueScoreDetail.modalOpen}
                  preSet="判断题选择"
                  onChange={choiceJudgeQue}
                  value={judgeQueScoreDetail.questionsModalVal}
                ></SourceSelectModal>
              </div>
            </YmCollaPanes>
          </Form>
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
}

export { AddTestPaper };
